package com.elinkway.infinitemovies.download;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.widget.Toast;

import com.elinkway.infinitemovies.application.MoviesApplication;
import com.elinkway.infinitemovies.ui.activity.DownloadActivity;
import com.elinkway.infinitemovies.utils.LogCat;
import com.elinkway.infinitemovies.utils.LogUtils;
import com.elinkway.infinitemovies.utils.NetWorkTypeUtils;
import com.le123.ysdq.R;


public class DownloadBroadcastReceiver extends BroadcastReceiver {

	public static final String TAG = "DownloadBroadcastReceiver";
	public static final String NET_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
	private final static String DOWNLOADCAN3G =  "com.funshion.video.DOWNLOADCAN3G";
	public static final String SPEED_ACTION =  "com.funshion.video.CUTDOWNLOADSPEED";
	public static final String SDCARD_NOSPACE_ACTION = "com.kuaikan.SDCARDNOSPACE";
	private final static int FAILURE = 1;
	public final static int NOTIFICATION_ID = "DownloadBroadcastReceiver".hashCode();
	public boolean onlyFirst = true;

	public static void setNotification(Context context, String title, String description) {
		LogUtils.i(TAG, "set notification");
		// 判断当前应用是否在前台
		final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

		// params
		int smallIconId = R.drawable.ic_launcher;
		Bitmap largeIcon = ((BitmapDrawable) context.getResources()
				.getDrawable(R.drawable.ic_launcher)).getBitmap();
		String info = description;

		Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
		intent.setPackage((String) null);
		intent.addFlags(268435456);

		// action when clicked
//		Intent intent = new Intent(context.getApplicationContext(), DownloadActivity.class);
//		intent.setAction(Intent.ACTION_VIEW);

		builder.setLargeIcon(largeIcon)
				.setSmallIcon(smallIconId)
				.setContentTitle(title)
				.setContentText(info)
				.setTicker(info)
				.setContentIntent(PendingIntent.getActivity(context, 0, intent, 0));

		final Notification n = builder.getNotification();
		n.flags |= Notification.FLAG_AUTO_CANCEL;
		nm.notify(NOTIFICATION_ID, n);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		if (null != context && null != intent) {
			String action = intent.getAction();
			if (TextUtils.isEmpty(action)) {
				return;
			}
			LogCat.e(TAG, "action == " + action);
			// 网络发生变化时
			if (NET_ACTION.equals(action)) {
				onlyFirst = true;
				ConnectivityManager manager = (ConnectivityManager) context
						.getSystemService(Context.CONNECTIVITY_SERVICE);
				if (null == manager) {
					return;
				}
				NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
				NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
				if (null == wifi || null == gprs) {
					return;
				}
				if (wifi.isConnected()) {
					LogCat.e(TAG, "wifi is connected ");
					for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
						LogUtils.e(TAG, "wifi connected job's status is " + job.getStatus() + " " + job.getIsAllow3GDownload() + " " +
						onlyFirst + " " + job.getLastConnectivityState());
						if (null != job && job.getStatus() == DownloadJob.NO_USER_PAUSE) {
							if(job.getExceptionType() != DownloadJob.NO_SD
									&& job.getExceptionType() != DownloadJob.FILE_NOT_FOUND) {
								job.start();
								if (MoviesApplication.getInstance().getRunningPackageName().equals(MoviesApplication
										.YINGSHIDAQUAN_PACKAGENAME)) {
									Toast.makeText(context, context.getResources().getString(R.string.continue_download_wifi), Toast.LENGTH_SHORT).show();
								} else {
									setNotification(context, context.getResources().getString(R.string.download_pause_title),
											context.getResources().getString(R.string.continue_download_wifi));
								}

							}
						} else if (null != job && job.getStatus() == DownloadJob.PAUSE && job.getIsAllow3GDownload() && onlyFirst
						    && job.getLastConnectivityState() == NetWorkTypeUtils.TYPE_MOBILE){
							onlyFirst = false;
							if (MoviesApplication.getInstance().getRunningPackageName().equals(MoviesApplication
									.YINGSHIDAQUAN_PACKAGENAME)) {
								Toast.makeText(context, context.getResources().getString(R.string.please_continue_by_hand), Toast.LENGTH_SHORT).show();
							} else {
								setNotification(context, context.getResources().getString(R.string.download_pause_title),
										context.getResources().getString(R.string.please_continue_by_hand));
							}
						}
						job.setLastConnectivityState(NetWorkTypeUtils.TYPE_WIFI);
					}
					// wifi连接，自动继续下载升级包文件
//					AutoDownloadApkSupporter mDownloadApkInstance = AutoDownloadApkSupporter.getInstance();
//					if (mDownloadApkInstance.getAutoDownloadUpdateFileState() == FAILURE) {
//						mDownloadApkInstance.reDownloadUpgradeApk(context, mDownloadApkInstance.getmUpgradeUrl());
//					}

//					AdShowUtils.mApkDownloadPauseFlag = false;
//					reDownloadApk(context);
				}
				if (gprs.isConnected()) {
//					P2pHelper p2pHelper =P2pHelper.getInstance();
//					p2pHelper.stopTaskOnPauseOrWait();
//					p2pHelper.stopAllTaskOn3G();
					LogCat.e(TAG, "gprs connected");
					DownloadManager downloadManager = MoviesApplication.getInstance().getDownloadManager();
					for (DownloadJob job : downloadManager.getQueuedDownloads()) {
//						p2pHelper.stopDownloadTask(job);
						LogUtils.e(TAG, "gprs connected status is " + job.getStatus() + " " + job.getLastConnectivityState());
						if (job.getStatus() == DownloadJob.DOWNLOADING && job.getLastConnectivityState() ==
								NetWorkTypeUtils.TYPE_WIFI) {
							if (!job.getIsAllow3GDownload()) {
								job.pauseOnOther(DownloadJob.NO_USER_PAUSE);
								if (MoviesApplication.getInstance().getRunningPackageName().equals(MoviesApplication
										.YINGSHIDAQUAN_PACKAGENAME)) {
									Toast.makeText(context, context.getResources().getString(R.string.pause_download_mobile), Toast.LENGTH_SHORT).show();
								} else {
									setNotification(context, context.getResources().getString(R.string.download_pause_title),
											context.getResources().getString(R.string.pause_download_mobile));
								}
							} else {
								if (MoviesApplication.getInstance().getRunningPackageName().equals(MoviesApplication
										.YINGSHIDAQUAN_PACKAGENAME)) {
									Toast.makeText(context, context.getResources().getString(R.string.continue_download_mobile), Toast.LENGTH_SHORT).show();
								} else {
									setNotification(context, context.getResources().getString(R.string.download_pause_title),
											context.getResources().getString(R.string.continue_download_mobile));
								}
							}
						}
						if (job.getStatus() == DownloadJob.NO_USER_PAUSE && job.getIsAllow3GDownload()) {
							job.start();
							if (MoviesApplication.getInstance().getRunningPackageName().equals(MoviesApplication
									.YINGSHIDAQUAN_PACKAGENAME)) {
								Toast.makeText(context, context.getResources().getString(R.string.continue_download_no_net_to_mobile), Toast.LENGTH_SHORT).show();
							} else {
								setNotification(context, context.getResources().getString(R.string.download_pause_title),
										context.getResources().getString(R.string.continue_download_no_net_to_mobile));
							}
						}
						job.setLastConnectivityState(NetWorkTypeUtils.TYPE_MOBILE);
					}
				}
				if (wifi.getState() != null && gprs.getState() != null && !wifi.isConnected() && !gprs.isConnected()) {
					LogCat.e(TAG, "no network");
					DownloadManager downloadManager = MoviesApplication.getInstance().getDownloadManager();
					for (DownloadJob job : downloadManager.getQueuedDownloads()) {
//						p2pHelper.stopDownloadTask(job);
						if (job.getStatus() == DownloadJob.DOWNLOADING) {
							job.pauseOnOther(DownloadJob.NO_USER_PAUSE);
							if (MoviesApplication.getInstance().getRunningPackageName().equals(MoviesApplication
									.YINGSHIDAQUAN_PACKAGENAME)) {
								Toast.makeText(context, context.getResources().getString(R.string.pause_download_no_network), Toast.LENGTH_SHORT).show();
							} else {
								setNotification(context, context.getResources().getString(R.string.download_pause_title),
										context.getResources().getString(R.string.pause_download_no_network));
							}
						}
						job.setLastConnectivityState(NetWorkTypeUtils.NETTYPE_NO);
					}
				}
			}

			if (DOWNLOADCAN3G.equals(action)) {
				boolean isDownloadcan3g = intent.getBooleanExtra("isDownloadcan3g", false);
				// 当非移动网络时
				if (!(NetWorkTypeUtils.reportNetType(MoviesApplication.getInstance()) == 2))
					return;
				if (!isDownloadcan3g) {
					for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
						if (null != job && job.getStatus() == DownloadJob.DOWNLOADING)
							job.pauseOnOther(DownloadJob.NO_USER_PAUSE);
					}
				} else {
					for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
						if (null != job && job.getStatus() == DownloadJob.NO_USER_PAUSE) {
							if(job.getExceptionType() != DownloadJob.NO_SD
									&& job.getExceptionType() != DownloadJob.FILE_NOT_FOUND) {
								job.start();
							}
						}
					}
				}
			}
			
			if(SDCARD_NOSPACE_ACTION.equals(action)){
				for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
					if (null != job && job.getStatus() == DownloadJob.DOWNLOADING)
						job.pauseOnOther(DownloadJob.NO_USER_PAUSE);
				}
			}

			if (SPEED_ACTION.equals(action)) {
				boolean cutSpeed = intent.getBooleanExtra("player", false);
				MoviesApplication.getInstance().setSpeedCut(cutSpeed);
				if (cutSpeed) {
					for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
						if (null != job && job.getStatus() == DownloadJob.DOWNLOADING) {
							job.pauseOnOther(DownloadJob.NO_USER_PAUSE);
						}
						MoviesApplication.getInstance().getDownloadManager().notifyObservers();
					}
//					AdShowUtils.mApkDownloadPauseFlag = true;
//					LogUtils.i(TAG, "AdShowUtils.mApkDownloadPauseFlag被赋值为 " + AdShowUtils.mApkDownloadPauseFlag);
				} else {
					for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
						if (null != job && job.getStatus() == DownloadJob.NO_USER_PAUSE) {
							if(job.getExceptionType() != DownloadJob.NO_SD
									&& job.getExceptionType() != DownloadJob.FILE_NOT_FOUND) {
								job.start();
							}
						}
					}
//					ConnectivityManager manager = (ConnectivityManager) context
//							.getSystemService(Context.CONNECTIVITY_SERVICE);
//					if (null == manager) {
//						return;
//					}
//					NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//					if (null != gprs && !gprs.isConnected()) {
////						AdShowUtils.mApkDownloadPauseFlag = false;
////						reDownloadApk(context);
//					}
//					P2pHelper.getInstance().stopTaskOnPauseOrWait();
				}
			}

			if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
				for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
//					if (null != job && job.getStatus() == DownloadJob.NO_USER_PAUSE)
//						job.start();
					if (DownloadActivity.mSizeManager != null) {
//						DownloadActivity.mSizeManager.ansynHandlerSdcardSize();
					}
				}
			}

			if (Intent.ACTION_MEDIA_REMOVED.equals(action) || Intent.ACTION_MEDIA_EJECT.equals(action)
					|| Intent.ACTION_MEDIA_BAD_REMOVAL.equals(action)) {
				for (DownloadJob job : MoviesApplication.getInstance().getDownloadManager().getQueuedDownloads()) {
					if (null != job && job.getStatus() == DownloadJob.DOWNLOADING) {
						job.setExceptionType(DownloadJob.NO_SD);
						job.pauseOnOther(DownloadJob.NO_USER_PAUSE);
					}
				}
			}

			if (Intent.ACTION_MEDIA_MOUNTED.equals(action)) {

			}
			if (Intent.ACTION_MEDIA_EJECT.equals(action)) {

			}
		}
	}

//	private void reDownloadApk(Context context) {
//		ArrayList<AdApkEntity> apkList = MoviesApplication.getInstance().getmAdDownloadAppList();
//		if (null != apkList && apkList.size() > 0) {
//			// for(AdApkEntity entity : apkList) {
//			for (int i = 0; i < apkList.size(); i++) {
//				AdApkEntity entity = apkList.get(i);
//				AdShowUtils.startDownload(context, entity.getDownloadUrl(), entity.getNotifyId());
//				LogUtils.i(TAG, "start apk download -- url == " + entity.getDownloadUrl());
//			}
//		}
//		LogUtils.i(TAG, "start download -- mApkDownloadPauseFlag == " + AdShowUtils.mApkDownloadPauseFlag);
//	}

}
